<template>
  <div>
    <Card dis-hover style="margin: 10px">
      <Form ref="form1" :model="form1" :label-width="120">
        <div v-if="switchFlag">
          <Row :gutter="16" class="query-form2">
            <i-col span="8">
              <FormItem label="流程图名称：">
                <Input class="query-form-el" type="text" v-model="procinstName" placeholder="请输入流程名称"></Input>
              </FormItem>
            </i-col>
            <i-col span="8">
              <FormItem label="上报人：">
                <Input class="query-form-el" type="text" v-model="userName" placeholder="请输入上报人"></Input>
              </FormItem>
            </i-col>
            <i-col span="8">
              <FormItem label="上报时间：">
                <DatePicker class="query-form-el" type="daterange" placement="bottom-end" v-model="dateRange"
                            placeholder="请选择上报时间（开始，结束）"></DatePicker>
              </FormItem>
            </i-col>
          </Row>
          <Row :gutter="16" class="query-form2">
            <i-col span="24">
              <div style="float: right">
                <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
                <Button @click="switchQuery(false)" style="margin-left: 10px" class="ivu-btn-switch2" type="text">收起
                  <Icon type="ios-arrow-up"/>
                </Button>
              </div>
            </i-col>
          </Row>
        </div>
        <div v-else>
          <Row :gutter="16" class="query-form2">
            <i-col span="8">
              <FormItem label="流程图名称：">
                <Input class="query-form-el" type="text" v-model="procinstName" placeholder="请输入流程名称"></Input>
              </FormItem>
            </i-col>
            <i-col span="8">
              <FormItem label="上报人：">
                <Input class="query-form-el" type="text" v-model="userName" placeholder="请输入上报人"></Input>
              </FormItem>
            </i-col>
            <i-col span="8">
              <div style="float: right">
                <Button class="ivu-btn-query" icon="md-search" @click="query">查询</Button>
                <Button class="ivu-btn-reset" style="margin-left: 10px" @click="reset">重置</Button>
                <Button @click="switchQuery(true)" style="margin-left: 5px" class="ivu-btn-switch2" type="text">展开
                  <Icon type="ios-arrow-down"/>
                </Button>
              </div>
            </i-col>
          </Row>
        </div>
      </Form>
      <Table ref='table' style="margin-top: 10px" :loading="loading" border :columns="columns1"
             no-data-text="没有查询到相关数据！"
             :data="dataTable" width="100%" :height="tableHeight" highlight-row stripe size="small"></Table>
      <Row type="flex" justify="end">
        <i-col>
          <Page :total="pagedata.total" :current="pagedata.currentPage" :page-size="pagedata.pageSize"
                @on-page-size-change="pageSizeChange" @on-change="pageChange" :page-size-opts="pageSizeArray" show-total
                show-sizer show-elevator/>
        </i-col>
      </Row>
      <Modal :transfer=false v-model="model1" :width=900>
        <Tabs>
          <TabPane label="历史记录">
            <Table ref='table' border :columns="columns2" no-data-text="没有查询到相关数据！" style="margin-top: 0"
                   :loading="loading2"
                   :data="history" width="100%" :height="450" highlight-row stripe size="small"></Table>
          </TabPane>
          <TabPane label="流程图">
            <div style="height: 450px; overflow-y: auto; overflow-x: auto">
              <img :src="imgUrl">
            </div>
          </TabPane>
          <TabPane label="人员变更记录">
              <Table ref='table' border :columns="columns3" no-data-text="没有查询到相关数据！" style="margin-top: 0"
                     :loading="loading2"
                     :data="historyChange" width="100%" :height="450" highlight-row stripe size="small"></Table>
          </TabPane>
        </Tabs>
        <div slot="footer">
          <Button @click="model1=false" class="ivu-btn-save">关闭</Button>
        </div>
      </Modal>
    </Card>

    <Modal title="流程委办" :transfer=false v-model="model3"  :width=900>
        <Form :label-width="130" ref="formCustom" :model="form1data" :rules="ruleCustom">
            <Row :gutter="16">
                <i-col span="24">
                    <FormItem label="当前节点：" prop="oldUserId">
                        <Select label-in-value v-model="form1data.oldUserId" @on-change="changeType">
                            <Option v-for="item in taskType" :value="item.value" :key="item.value">{{ item.label }}</Option>
                        </Select>
                    </FormItem>
                </i-col>
            </Row>
            <Row :gutter="16">
                <i-col span="24">
                    <FormItem label="当前执行人：" prop="oldUserName">
                        <Input type="text" v-model="form1data.oldUserName" disabled/>
                    </FormItem>
                </i-col>
            </Row>
            <Row :gutter="16">
                <i-col span="24">
                    <FormItem label="指定委办人：">
                        <Input class=''placeholder="请选择委办人" type='text' v-model='form1data.newUserName' @on-focus="openSelect"></Input>
                    </FormItem>
                </i-col>
            </Row>
        </Form>
        <div slot="footer">
            <Button @click="canal()" class='ivu-btn-cancel' style="margin-left: 8px">关闭</Button>
            <Button @click="assignSubmit()" :loading="loading" class='ivu-btn-save'>提交</Button>
        </div>
    </Modal>
    <UserForTaskSelect :usersListModal="usersListModal" @closeDialog="closeDialog" @getSelectData="setPeople">
    </UserForTaskSelect>
  </div>
</template>

<script>
import {Api} from '../../../api/index.js'
import {sessionStorage, cookie} from '../../../common/cacheUtils.js';
import UserForTaskSelect from './userForTaskSelect.vue'

export default {
  components: {
    UserForTaskSelect
  },
  data() {
    return {
      procinstName: '',
      userName: '',
      dateRange: ["", ""],
      createDate: '',
      endDate: '',
      switchFlag: false,
      imgUrl: '',
      loading: false,
      loading2: false,
      form1: {},
      //分页参数
      pageSizeArray: [10, 20, 50],
      pagedata: {
        total: 0,
        pageSize: 10,
        currentPage: 1,
      },
      columns1: [
        {
          type: 'index',
          title: '序号',
          minWidth: 80,
          align: 'center',
        },
        {
          minWidth: 250,
          title: '流程名称',
          align: 'center',
          key: 'procinstName',
        },
        {
          minWidth: 120,
          title: '流程状态',
          key: 'procinstStateName',
          align: 'center',
          render:(h,params)=>{
            return h('div', [
              h('span', {
                style: {
                  color: params.row.procinstStateName == '被退回' ? 'red': 'green'
                }
              }, params.row.procinstStateName)
            ]);
          }
        },
        {
          minWidth: 150,
          title: '上报时间',
          key: 'createDate',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              (this.formatDate(new Date(params.row.createDate), 'yyyy-MM-dd hh:mm:ss'))
            ]);
          }
        },
        {
          minWidth: 150,
          title: '上报人',
          key: 'userName',
          align: 'center'
        },
        {
          minWidth: 200,
          title: '当前任务节点名称',
          key: 'taskName',
          align: 'center'
        },
        {
          title: '操作',
          key: 'action',
          fixed: 'right',
          minWidth: 200,
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h('a', {
                props: {
                  type: 'primary',
                },
                style: {
                  fontSize: '14px',
                },
                on: {
                  click: () => {
                    this.showData(params.row);
                  }
                }
              }, '审批'),
              h('Divider', {
                  props: {
                      type: 'vertical',
                  }
              }, ''),
			  h('Tooltip', {
                  props: {
			          type: 'vertical',
			      }
			    },[ h('A', {
					  props: {
                      type: 'primary',
                      size: 'small'
                  },
                  style: {
                      fontSize: '14px',
                  },
                  on: {
                      click: () => {
                          this.flowRemedy(params.row);
                      }
                  }
              }, '委办'),
					h('span', {
						slot: 'content',
						style: {
							whiteSpace: 'normal',
							wordBreak: 'break-all'
						}
					}, '委托他人代为办理')
			  ]),
              /*    h('Divider', {
                      props: {
                          type: 'vertical',
                      }
                  }, ''),
                  h('a', {
                      props: {
                          type: 'primary',
                      },
                      style: {
                          fontSize: '14px',
                      },
                      on: {
                          click: () => {
                              this.revokeTask(params.row);
                          }
                      }
                  }, '撤回'), */
              h('Divider', {
                props: {
                  type: 'vertical',
                }
              }, ''),
              h('a', {
                props: {
                  type: 'primary',
                },
                style: {
                  fontSize: '14px',
                },
                on: {
                  click: () => {
                    this.imgUrl = Api.getFlowImg + '/' + params.row.procinstId
                    this.showHistory(params.row);
                  }
                }
              }, '审批记录')
            ]);
          }
        }
      ],
      dataTable: [],
      tableHeight: 10,
      model1: false,
      model2: false,
      model3 : false,
      form1data: {},
      ruleCustom: {
        newUserId: [
          {
            required: true,
            message: '  ',
            trigger: 'blur,change'
          }
        ],
      },
      usersListModal:false,
      taskType: [],
      taskId:"",
      resultData: {},
      history: [],
      columns2: [
        {
          type: 'index',
          title: '序号',
          width: 80,
          align: 'center',
        },
        {
          width: 180,
          title: '审批时间',
          key: 'endTime',
          align: 'center',
        },
        {
          width: 185,
          title: '节点名称',
          key: 'name',
          align: 'center',
        },
        {
          width: 120,
          title: '审批人',
          key: 'userName',
          align: 'center'
        },
        {
          width: 100,
          title: '审批意见',
          key: 'route',
          align: 'center'
        },
        {
          width: 200,
          title: '备注',
          key: 'opinions',
          align: 'center'
        },
      ],
      columns3: [
          {
              type: 'index',
              title: '序号',
              width: 80,
              align: 'center',
          },
          {
              title: '变更节点',
              key: 'taskName',
              align: 'center',
          },
          {
              title: '变更前审批人',
              key: 'oldUserName',
              align: 'center',
          },
          {
              title: '变更后审批人',
              key: 'newUserName',
              align: 'center',
          },
      ],
      historyChange: []
    }
  },
  watch: {
    "model1": function (qw, er) {
      if (!qw) {
        this.imgUrl = '';
      }
    },
  },
  mounted: function () {
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop - 215;
    this.query();
  },
  methods: {
    switchQuery(flag) {
      this.switchFlag = flag;
      if (this.switchFlag) {
        this.tableHeight = this.tableHeight - 30;
      } else {
        this.tableHeight = this.tableHeight + 30;
      }
    },
    pageChange(pageNum) {
      this.pagedata.currentPage = pageNum;
      this.query();
    },
    pageSizeChange(pageSize) {
      this.pagedata.pageSize = pageSize;
      this.query();
    },
    showData(row) {
      let user = sessionStorage('userId').getObject('userId');
      let formKey = row.formKey;
      let data = {
        taskName: row.taskName,
        taskId: row.taskId,
        workId: row.workId,
        procinstId: row.procinstId,
        procinstState: row.procinstState,
        currentTask: row.currentTask,
        close: false,
        viewFlag: false,
        userId: user.userId,
        reportUserId: row.createUserId,
      }
      this.$router.push({path: "/" + formKey, query: data});
    },
    revokeTask(row) {
      let user = sessionStorage('userId').getObject('userId');
      this.$http.get(Api.revokeTask + '/' + row.taskId + '/' + user.userId + '/' + row.procinstId).then((res) => {
        console.log(res.data);
      })
    },
    showHistory(row) {
      this.model1 = true;
      this.loading2 = true;
      this.$http.get(Api.getHistory + '/' + row.procinstId, {params: {}}).then((res) => {
        this.history = res.data;
        this.loading2 = false;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      });
      this.$http.get(Api.getHistory + '/change/' + row.procinstId, {params: {}}).then((res) => {
        this.historyChange = res.data;
      }).catch(e => {
        this.$Message.error("数据获取失败")
      });
    },
    reset() {
      this.dateRange = ["", ""]
      this.userName = "";
      this.procinstName = "";
      this.query();
    },
    query() {
      this.createDate = "";
      this.endDate = "";
      this.$emit("refreshTodo");
      if (this.dateRange[0] != "" && this.dateRange[1] != "") {
        this.createDate = this.formatDate(new Date(this.dateRange[0]), 'yyyy-MM-dd');
        this.endDate = this.formatDate(new Date(this.dateRange[1]), 'yyyy-MM-dd');
      }
      let user = sessionStorage('userId').get('userId');
      let userJson = JSON.parse(user);
      let data = {
        currentPage: this.pagedata.currentPage,
        size: this.pagedata.pageSize,
        // createUserId: userJson.userId,
        procinstName: this.procinstName,
        userName: this.userName,
        startDate: this.createDate != "" ? this.createDate + " 00:00:00" : "",
        endDate: this.endDate != "" ? this.endDate + " 23:59:59" : "",
      }
      let url = Api.getToDoList;
      this.loading = true;
      this.$http.get(url, {params: data}).then((res) => {
        this.dataTable = res.data.data;
        if (this.dataTable != undefined) {
          this.dataTable.map(item => {
            if (item.procinstState == '0' || item.procinstState == null) {
              item.procinstStateName = '未上报';
            } else if (item.procinstState == '1') {
              item.procinstStateName = '审批中';
            } else if (item.procinstState == '2') {
              item.procinstStateName = '被退回';
            } else if (item.procinstState == '3') {
              item.procinstStateName = '已审批';
            } else if (item.procinstState == '4' && (item.procinstName == '企业安全总监推荐流程' || item.procinstName == '企业安全总监变更流程')) {
              item.procinstStateName = '被退回';
            }else if (item.procinstState == '6' && (item.procinstName == '企业安全总监推荐流程' || item.procinstName == '企业安全总监变更流程')) {
              item.procinstStateName = '被退回';
            }
          })
        }
        this.pagedata.total = res.data.totalSize;
        this.loading = false;
      }).catch(e => {
        this.loading = false;
        this.$Message.error("数据获取失败")
      })
    },
    setPeople(user){
        this.form1data.newUserId = user.userId;
        this.form1data.newUserName = user.userName;
        this.usersListModal = false;
    },
    closeDialog(){
        this.usersListModal = false;
    },
    openSelect(){
      this.usersListModal = true;
    },
    flowRemedy(data){
        this.form1data= {};
        this.form1data.formKey = data.formKey;
        this.form1data.taskName = data.taskName;
        this.form1data.workId = data.workId;
        this.$http.get(Api.getRemedy + '/'+ data.procinstId ,{
            params:{}
        }).then((res) => {
            this.taskType = res.data.data;
            this.resultData = res.data;
            this.model3 = true;
        }).catch( e => {
            this.$Message.error('请求失败');
        })
    },
    changeType() {
        let type = this.form1data.oldUserId;
        this.form1data.oldUserName = this.resultData[type].userName;
        this.taskId =  this.resultData[type].taskId;
        if(this.taskId == ''){
            this.taskType.forEach(i=>{
                if(i.label == val.label){
                    this.taskId = i.taskId;
                }
            })
        }
    },
    assignSubmit(){
        if( this.form1data.newUserId ==  this.form1data.oldUserId){
            this.$Message.error('不支持委办给本人，请修改！');
            return;
        }
        if( this.form1data.newUserId == undefined || this.form1data.newUserId == null || this.form1data.newUserId == ''){
          this.$Message.error('请选择指定委派人！');
          return;
        }
        let data = {
            oldUserId : this.form1data.oldUserId,
            newUserId : this.form1data.newUserId
        };
        this.$refs['formCustom'].validate((valid) => {
            if(valid) {
                this.loading = true;
                this.$http.get(Api.getAssign + this.taskId , {params : data}).then((res) => {
                  this.loading = false;
                  this.model3 = false
                  this.$Message.success('委办成功');
                  this.query();
                  if(res.data.status == 200){
                    if (this.form1data.formKey == 'briefingListForApproval'){
                      let brief = {briefId:this.form1data.workId};
                      if (this.form1data.taskName == '企业负责人审批'){
                        brief.chargeId = this.form1data.newUserId;
                        brief.charge = this.form1data.newUserName;
                      }else if (this.form1data.taskName == '二级集团安全环保管理人员审批'){
                        brief.secondaryGroupPersionId = this.form1data.newUserId;
                        brief.secondaryGroupPersion = this.form1data.newUserName;
                      }else if(this.form1data.taskName == '集团安全环保管理人员审批'){
                        brief.groupPersionId = this.form1data.newUserId;
                        brief.groupPersion = this.form1data.newUserName;
                      }
                      let url = Api.briefing;
                      brief.updateUserId = sessionStorage('userId').getObject('userId').userId
                      brief.updateOrgId = sessionStorage('userId').getObject('userId').orgInfo.orgId
                      this.$http.put(url, brief).then((res) => {
                      }).catch(e => {
                        this.$Message.error('请求失败');
                      })
                    }
                  }
                }).catch(e => {
                    this.$Message.error('请求失败'+e);
                });
            }
        });
    },
    canal(){
        this.model3 = false;
    },
    formatDate(date, fmt) {
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      let o = {
        'M+': date.getMonth() + 1,
        'd+': date.getDate(),
        'h+': date.getHours(),
        'm+': date.getMinutes(),
        's+': date.getSeconds()
      };
      for (let k in o) {
        if (new RegExp(`(${k})`).test(fmt)) {
          let str = o[k] + '';
          fmt = fmt.replace(RegExp.$1, RegExp.$1.length === 1 ? str : this.padLeftZero(str));
        }
      }
      return fmt;
    },
    padLeftZero(str) {
      return ('00' + str).substr(str.length);
    },

  },
}
</script>
<style scoped>
@import '../../../index.css';

</style>
